package com.book.remote;

import com.book.activeMQ.productor.ProductMQ;
import com.book.common.BookStatusEnum;
import com.book.common.BookTypeEnum;
import com.book.dto.BookDto;
import com.book.dto.UserDto;
import com.book.pojo.Category;
import com.book.service.BookService;
import com.book.service.CategoryService;
import com.book.service.ImgService;
import com.book.service.UserService;
import com.book.util.EhCacheManager;
import com.book.vo.BookIndexVo;
import com.book.vo.BookNewVo;
import com.book.vo.OrderBookVo;
import com.book.vo.UBookVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 李锦程
 * @Date 2021/4/2 3:49 下午
 * @Package com.book.service.impl
 * @Version 1.0
 */
@Slf4j
@Component
public class BookApiRemote {
    @Autowired
    private BookService uBookService;
    @Autowired
    private EhCacheManager ehCacheManager;
    @Autowired
    private UserService userService;
    @Autowired
    private ImgService imgService;
    @Autowired
    private ProductMQ productMQ;
    @Autowired
    private CategoryService categoryService;

    public List<BookIndexVo> getUBookList() {
        Object o = ehCacheManager.get("myCache", "bookList");
        if (o != null) {
            log.info("object:{}", o);
            List<BookIndexVo> voList = (List<BookIndexVo>) o;
            return voList;
        } else {
            List<BookDto> uBookList = uBookService.getUBookList();
            if (CollectionUtils.isEmpty(uBookList)) {
                return null;
            }
            List<BookIndexVo> voList = covertDtoList(uBookList);
            ehCacheManager.put("myCache", "bookList", voList);
            return voList;
        }
    }

    public Integer saveUBook(BookDto uBookDto) {
        Integer integer = uBookService.addUBook(uBookDto);
        if (integer != 0) {
            ehCacheManager.evict("myCache", "bookList");
        }
        return integer;
    }

    public BookDto getBookById(Integer id) {
        try {
            if (id == null) {
                return new BookDto();
            }
            return (BookDto) uBookService.selectById(id);
        } catch (Exception e) {
            log.error("UBookApiImpl.getBookById#id:{}", id, e);
            return new BookDto();
        }
    }

    public Integer upDataUBook(BookDto uBookDto) {
        try {
            log.info("UBookApiImpl.getBookById#uBookDto:{}", uBookDto);
            return uBookService.updateSelective(uBookDto);
        } catch (Exception e) {
            log.error("UBookApiImpl.getBookById#uBookDto:{}", uBookDto, e);
            return 0;
        }
    }

    public UBookVo getUBookDetail(Integer id) {
        try {
            log.info("UBookApiImp.getUBookDetail#id:{}", id);
            UBookVo uBookVo = new UBookVo();
            BookDto o = (BookDto) uBookService.selectById(id);
            if (o != null) {
                uBookVo.setUBookDto(o);
                UserDto u = userService.getUserById(o.getUId());
                u.setUPass(null);
                uBookVo.setUserDto(u);
            }
            List<String> imgByBookCode = imgService.getImgByBookCode(uBookVo.getUBookDto().getBookCode());
            uBookVo.setImgUrl(imgByBookCode);
            assert o != null;
            Category category1 = categoryService.getCategoryById(o.getClassId());
            Category category2 = categoryService.getCategoryById(category1.getId());
            uBookVo.setFirstCategory(category2.getCname());
            uBookVo.setSecondCategory(category1.getCname());
            uBookVo.setType(BookTypeEnum.getMsg((int) o.getBookNeed()));
            return uBookVo;
        } catch (Exception e) {
            log.error("UBookApiImpl.getuBookDetail#id:{}", id, e);
            return null;
        }
    }

    public UBookVo getBookByBookCode(String bookCode) {
        OrderBookVo orderBookVo = new OrderBookVo();

        BookDto uBookByCode = uBookService.getUBookByCode(bookCode);
        UBookVo uBookVo = new UBookVo();
        if (uBookByCode != null) {
            orderBookVo.setBookCode(uBookByCode.getBookCode());
            orderBookVo.setBookName(uBookByCode.getBookTitle());
            orderBookVo.setNum(1);
            orderBookVo.setPrice(uBookByCode.getBookPrice());
            orderBookVo.setBookAuthor(uBookByCode.getBookAuthor());
            uBookVo.setUBookDto(uBookByCode);
            UserDto u = userService.getUserById(uBookByCode.getUId());
            u.setUPass(null);
            uBookVo.setUserDto(u);
        }
        List<String> imgByBookCode = imgService.getImgByBookCode(uBookVo.getUBookDto().getBookCode());
        uBookVo.setImgUrl(imgByBookCode);
        assert uBookByCode != null;
        Category category1 = categoryService.getCategoryById(uBookByCode.getClassId());
        Category category2 = categoryService.getCategoryById(category1.getId());
        uBookVo.setFirstCategory(category2.getCname());
        uBookVo.setSecondCategory(category1.getCname());
        uBookVo.setType(BookTypeEnum.getMsg((int) uBookByCode.getBookNeed()));
        log.info("BookApiRemote.getBookByBookCode#bookVo:{}",uBookVo);
        return uBookVo;

    }

    public List<BookNewVo> getBookThree() {
        List<BookDto> bookThree = uBookService.getBookThree();
        log.info("BookApiRemote#list:{}", bookThree);
        List<BookNewVo> list = Lists.newArrayList();
        bookThree.forEach(m -> {
            BookNewVo newVo = new BookNewVo();
            newVo.setId(m.getId());
            newVo.setBookTitle(m.getBookTitle());
            newVo.setNote(m.getNote());
            List<String> imgByBookCode = imgService.getImgByBookCode(m.getBookCode());
            if (CollectionUtils.isNotEmpty(imgByBookCode)) {
                newVo.setImgUrl(imgByBookCode.get(0));
            }
            list.add(newVo);
        });
        log.info("BookApiRemote#newlist:{}", list);
        return list;
    }

    public List<BookIndexVo> getBookListByUId(Integer currentId) {
        log.info("BookApiRemote.getBookListByUId#uId:{}", currentId);
        try {
            List<BookDto> bookDtos = uBookService.getBookListByUId(currentId);
            log.info("BookApiRemote.getBookListByUId#uId:{},list:{}", currentId, bookDtos);
            if (CollectionUtils.isEmpty(bookDtos)) {
                return Lists.newArrayList();
            }
            List<BookIndexVo> voList = bookDtos.stream().map(this::covertBookDtoIndexVo).collect(Collectors.toList());
            log.info("BookApiRemote.getBookListByUId#voList:{}", voList);
            return voList;
        } catch (Exception e) {
            log.error("BookApiRemote.getBookListByUId异常#uId:{}", currentId, e);
            return Lists.newArrayList();
        }
    }

    private BookIndexVo covertBookDtoIndexVo(BookDto bookDto) {
        if (bookDto == null) {
            return null;
        }
        BookIndexVo bookIndexVo = new BookIndexVo();
        bookIndexVo.setId(bookDto.getId());
        bookIndexVo.setBookTitle(bookDto.getBookTitle());
        bookIndexVo.setBookPrice(bookDto.getBookPrice());
        bookIndexVo.setBookCode(bookDto.getBookCode());
        UserDto userById = userService.getUserById(bookDto.getUId());
        assert userById != null;
        bookIndexVo.setUserName(userById.getUName());
        List<String> imgByBookCode = imgService.getImgByBookCode(bookDto.getBookCode());
        if (CollectionUtils.isNotEmpty(imgByBookCode)) {
            bookIndexVo.setImgUrl(imgByBookCode.get(0));
        }
        bookIndexVo.setPostTime(sdf(bookDto.getBootTime()));
        bookIndexVo.setIsDelete(bookDto.getIsDelete());
        if (bookDto.getIsDelete() == 1){
            bookIndexVo.setStatus(BookStatusEnum.getMsg((int) bookDto.getBookFlag()));
        }else {
            bookIndexVo.setStatus("已失效");
        }
        return bookIndexVo;
    }

    private String sdf(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (date != null)
            return sdf.format(date);
        return null;
    }

    private List<BookIndexVo> covertDtoList(List<BookDto> dtos) {
        if (CollectionUtils.isEmpty(dtos)) {
            return Lists.newArrayList();
        }
        List<BookIndexVo> voList = Lists.newArrayList();
        dtos.forEach(m -> {
            BookIndexVo bookIndexVo = covertBookDtoIndexVo(m);
            UserDto userById = userService.getUserById(m.getUId());
            assert userById != null;
            bookIndexVo.setUserName(userById.getUName());
            voList.add(bookIndexVo);
        });
        return voList;
    }

    public List<BookIndexVo> queryAuthorOrTitle(Integer queryCode, String queryText) {
        log.info("BookApiRemote.queryAuthorOrTitle#queryCode:{},queryTitle:{}", queryCode, queryText);
        List<BookDto> dtos = uBookService.queryBookByAuthorOrTitle(queryCode, queryText);
        if (CollectionUtils.isEmpty(dtos)) {
            return Lists.newArrayList();
        }
        log.info("BookApiRemote.query#result{}", dtos);
        return dtos.stream().map(this::covertBookDtoIndexVo).collect(Collectors.toList());
    }

    public List<BookIndexVo> query(String queryText) {
        log.info("BookApiRemote.query#query:{}", queryText);
        List<BookIndexVo> voList = handleQuery(queryText);
        log.info("BookApiRemote.query#voList:{}", voList);
        return voList;
    }

    private List<BookIndexVo> handleQuery(String queryText) {
        List<BookDto> dtos = uBookService.queryBook(queryText);
        if (CollectionUtils.isEmpty(dtos)) {
            return Lists.newArrayList();
        }
        log.info("BookApiRemote.query#result{}", dtos);
        return dtos.stream().map(this::covertBookDtoIndexVo).collect(Collectors.toList());
    }

    public List<BookIndexVo> query(Integer categoryId,String queryText){
        List<Category> categoryList = categoryService.getCategoryList(categoryId);
        List<Integer> cateIdList = categoryList.stream().map(Category::getId).collect(Collectors.toList());
        List<BookDto> voList = uBookService.queryBook(cateIdList,queryText);
        log.info("BookRemote.query#voList:{}",voList);
        if (CollectionUtils.isEmpty(voList)){
            return Lists.newArrayList();
        }
        return voList.stream().map(this::covertBookDtoIndexVo).collect(Collectors.toList());
    }

    public List<BookIndexVo> searchFilter(Integer cataId, String price, boolean b) {
        if (b){
            List<BookDto> list = uBookService.searchFilter(cataId,price);
            if (CollectionUtils.isEmpty(list)){
                Lists.newArrayList();
            }
            return list.stream().map(this::covertBookDtoIndexVo).collect(Collectors.toList());
        }
        List<Category> categoryList = categoryService.getCategoryList(cataId);
        List<Integer> cateIdList = categoryList.stream().map(Category::getId).collect(Collectors.toList());
        List<BookDto> list = uBookService.searchFilter(cateIdList,price);
        if (CollectionUtils.isEmpty(list)){
            Lists.newArrayList();
        }
        return list.stream().map(this::covertBookDtoIndexVo).collect(Collectors.toList());
    }

    public Boolean deleteBookById(Integer id) {
        //校验订单是否完成
        Integer i = uBookService.deleteBookById(id);
        return i == 1;
    }

    public Boolean batchDeleteBook(List<Integer> ids){
        try {
            if (CollectionUtils.isEmpty(ids)){
                return false;
            }
            uBookService.batchDeleteBok(ids);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
